import cv2
image=cv2.imread(r'C:\Users\Administrator\Desktop\hat.png',cv2.IMREAD_GRAYSCALE)
#腐蚀
kernel1=cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
eroded_img1=cv2.erode(image,kernel1)
cv2.imshow("Output1",eroded_img1)
#膨胀
kernel1=cv2.getStructuringElement(cv2.MORPH_RECT,(6,6))
dilated_img1=cv2.dilate(image,kernel1,iterations=1)
cv2.imshow("Output2",dilated_img1)
#开运算
kernel=cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
image1=cv2.erode(image,kernel)
image2=cv2.dilate(image1,kernel)
cv2.imshow("Output3",image2)
#闭运算
kernel=cv2.getStructuringElement(cv2.MORPH_RECT,(5,5))
image1=cv2.dilate(image,kernel)
image2=cv2.erode(image1,kernel)
cv2.imshow("Output",image2)
#形态学梯度运算
kernel=cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
gradient =cv2.morphologyEx(image,cv2.MORPH_GRADIENT,kernel)
cv2.imshow("Output4",gradient)
#顶帽运算
tophat=cv2.morphologyEx(image,cv2.MORPH_TOPHAT,kernel)
cv2.imshow("Output5",tophat)
#黑帽运算
blackhat=cv2.morphologyEx(image,cv2.MORPH_BLACKHAT,kernel)
cv2.imshow("Output6",blackhat)
cv2.imshow("Output7",image)
#1
img_path=(r'C:\Users\Administrator\Desktop\buttons.png')
src=cv2.imread(img_path)
cv2.imshow("Output8",src)
oriImg=cv2.GaussianBlur(src,(3,3),0)
img=cv2.cvtColor(oriImg,cv2.COLOR_BGR2GRAY)
ret,img=cv2.threshold(img,250,255,cv2.THRESH_BINARY_INV)
cv2.imshow("Output9",img)
#2
kernel1=cv2.getStructuringElement(cv2.MORPH_RECT,(3,3))
eroded_img1=cv2.erode(image,kernel1)
cv2.imshow("Output10",img)
edges=cv2.morphologyEx(img,cv2.MORPH_GRADIENT,kernel)
cv2.imshow("Output11",edges)
#3
contours,hierarchy=cv2.findContours(edges,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
    x,y,w,h=cv2.boundingRect(contour)
    if w/h>0.7and w/h<1.3:
        cv2.rectangle(src,(x,y),(x+w,y+h),(0,0,255))
cv2.imshow("Output12",src)
num_buttons=len(contours)
print(f'检测到图像中纽扣的数量: {num_buttons}')
cv2.waitKey()
cv2.destroyAllWindows()